import { openDB } from 'idb';

// 数据库配置
const DB_NAME = 'ImageCacheDB';
const DB_VERSION = 1;
const STORE_NAME = 'images';

// 打开数据库并返回数据库实例
async function openImageDB() {
  const db = await openDB(DB_NAME, DB_VERSION, {
    upgrade(db) {
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        db.createObjectStore(STORE_NAME, { keyPath: 'url' });
      }
    }
  });
  return db;
}

// 获取缓存图片（Base64）
export async function getImageFromDB(url) {
  const db = await openImageDB();
  const tx = db.transaction(STORE_NAME, 'readonly');
  const store = tx.objectStore(STORE_NAME);
  const image = await store.get(url);
  return image ? image.base64 : null;
}

// 保存图片的 Base64 数据到 IndexedDB
export async function saveImageToDB(url, base64) {
  const db = await openImageDB();
  const tx = db.transaction(STORE_NAME, 'readwrite');
  const store = tx.objectStore(STORE_NAME);
  await store.put({ url, base64 });
  await tx.done;
}
